<?php

namespace app\admin\controller;

class Article extends Base
{
    public function articleList()
    {
        $articles = model('Article')->order(['aup' => 'desc', 'id' => 'desc'])->paginate(10);
        $viewData = [
            'articles' => $articles
        ];
        $this->assign($viewData);
        return view('articlelist');
    }

    public function articleAdd()
    {
        if (request()->isAjax()) {
            $data = [
                'title' => input('title'),
                'author' => input('author'),
                'tags' => input('tags'),
                'cateid' => input('cateid'),
                'desc' => input('desc'),
                'content' => input('content'),
                'aup' => input('aup')
            ];
            $result = model('Article')->add($data);
            if ($result == 1) {
                $this->success('文章发布成功！', 'admin/article/articlelist');
            }else {
                $this->error($result);
            }
        }
        $cates = model('Cate')->select();
        $viewData = [
            'cates' => $cates
        ];
        $this->assign($viewData);
        return view('articleadd');
    }

    public function articleUp()
    {
        $data = [
            'id' => input('id'),
            'aup' => input('aup') ? 0 : 1
        ];
        $result = model('Article')->isUpdate(true)->allowField(true)->save($data);
        if ($result) {
            $this->success('操作成功！', 'admin/article/articlelist');
        }else {
            $this->error('操作失败！');
        }
    }

    public function articleEdit()
    {
        if (request()->isAjax()) {
            $data = [
                'id' => input('id'),
                'title' => input('title'),
                'author' => input('author'),
                'tags' => input('tags'),
                'cateid' => input('cateid'),
                'desc' => input('desc'),
                'content' => input('content'),
                'aup' => input('aup')
            ];
            $result = model('Article')->edit($data);
            if ($result == 1) {
                $this->success('文章编辑成功！', 'admin/article/articlelist');
            }else {
                $this->error($result);
            }
        }
        $articleInfo = model('Article')->find(input('id'));
        $cates = model('Cate')->select();
        $viewData = [
            'articleInfo' => $articleInfo,
            'cates' => $cates
        ];
        $this->assign($viewData);
        return view('articleedit');
    }

    public function articleDel()
    {
        $articleInfo = model('Article')->find(input('id'));
        $result = $articleInfo->delete();
        if ($result) {
            $this->success('文章删除成功！', 'admin/article/articlelist');
        }else {
            $this->error('文章删除失败！');
        }
    }
}
